package eu.chargetime.ocpp.jsonserverimplementation.server.impl;

import cn.hutool.json.JSONUtil;
import eu.chargetime.ocpp.jsonserverimplementation.server.ISessionStoreService;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.core.RemoteStartTransactionRequest;
import eu.chargetime.ocpp.model.core.RemoteStopTransactionRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhaorui
 * @Date 2024/4/21  15:12
 * @description:
 */
@Service
@Slf4j
@AllArgsConstructor
public class SessionMemoryStoreImpl implements ISessionStoreService {

    /**
     * 缓存会话消息
     */
    private final ConcurrentHashMap<String, UUID> sessionStore = new ConcurrentHashMap();

    private final JsonServerImpl ocppServer;


    @Override
    public void put(String sessionId, UUID sessionIndex) {
        // 这里可以封装为物模型基础信息
        sessionStore.put(sessionId, sessionIndex);
        log.info("[put] 新增会话,sessionId:{}", sessionId);
    }

    @Override
    public void remove(String sessionId) {
        sessionStore.remove(sessionId);
        log.info("[remove] 移除会话,sessionId:{}", sessionId);
    }

    public Confirmation startMessage(String sessionId, String idTag) {

        UUID uuid = sessionStore.get(sessionId);
        if (Objects.isNull(uuid)) {
            log.error("[startMessage],会话不存在,sessionId:{},sessionStore:{}", sessionId, JSONUtil.toJsonStr(sessionStore));
        } else {
            RemoteStartTransactionRequest request = new RemoteStartTransactionRequest(idTag);
            Confirmation send = ocppServer.send(uuid, request);
            return send;
        }
        return null;
    }

    @Override
    public Confirmation stopMessage(final String sessionId, Integer transactionId) {
        UUID uuid = sessionStore.get(sessionId);
        if (Objects.isNull(uuid)) {
            log.error("[stopMessage],会话不存在,sessionId:{},sessionStore:{}", sessionId, JSONUtil.toJsonStr(sessionStore));
        } else {
            RemoteStopTransactionRequest request = new RemoteStopTransactionRequest(transactionId);
            Confirmation send = ocppServer.send(uuid, request);
            return send;
        }
        return null;
    }


}
